package com.winai.launcher.manager;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.baidu.location.BDLocation;
import com.ks.projectbasictools.base_interface.StringCallBack;
import com.ks.projectbasictools.okhttp.OkHttpUtils;
import com.ks.projectbasictools.utils.LogUtils;
import com.winai.launcher.bean.MojiBean;
import com.winai.launcher.bean.db.CurrentLocation;
import com.winai.launcher.bean.responseEntity.MojiEntity;
import com.winai.launcher.common.GlobalPublisher;
import com.winai.launcher.utils.BaseUtils;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;

public class WeatherManager {
    private final String TAG = "WeatherManager";
    private Context mContext;
    private static WeatherManager mInstance;

    private String productId = "279595160";
    private String apiKey = "73081f5892ac45f9bfbb036536892a22";
    private String pkg = "com.winai.launcher";
    private String signatuerSha256 = "CC:34:0C:96:78:D7:F2:2D:05:23:77:E0:CF:49:0C:BA:DE:E5:59:32:70:23:D2:FE:78:29:BC:E2:DD:8A:17:29";
    private String buildVariant = "release";

    private MojiEntity mMojiEntity;
    private CurrentLocation currentLocation = new CurrentLocation();
    private long sTime = 0;//请求的时间

    private WeatherManager(Context applicationContext) {
        this.mContext = applicationContext;
    }

    public static synchronized WeatherManager getInstance(Context mContext) {
        if (mInstance == null) {
            synchronized (WeatherManager.class) {
                if (null == mInstance) {
                    mInstance = new WeatherManager(mContext.getApplicationContext());
                }
            }
        }
        return mInstance;
    }

    /**
     * 说明：更新思必驰的城市定位信息配置
     */
    public void requestWeatherData() {
        BdLocationManager.getInstance().onStart(location -> {
            if (location == null) {
                Log.e(TAG, "获取位置失败，当前信息可能有误 -1");
                return;
            }
            if (location.getLocType() == BDLocation.TypeCriteriaException) {
                Log.e(TAG, "获取位置失败，当前信息可能有误 -2");
            } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
                Log.e(TAG, "获取位置失败，当前信息可能有误 -3");
            } else {
                //获取经度信息
                double longitude = location.getLongitude();
                //获取维度信息
                double latitude = location.getLatitude();
                if (longitude == 0 || latitude == 0 || longitude == 4.9E-324 || latitude == 4.9E-324) {
                    Log.e(TAG, "获取位置失败，当前信息可能有误 -4");
                    return;
                }
                String city = !TextUtils.isEmpty(location.getAddress().city)
                        ? location.getAddress().city
                        : "";
                String province = TextUtils.isEmpty(location.getAddress().province)
                        ? city.replace("市", "")
                        : location.getAddress().province;
                String district = !TextUtils.isEmpty(location.getAddress().district)
                        ? location.getAddress().district
                        : "";
                // 请求墨迹天气接口
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        requestMoji(province, city, district);
                    }
                }).start();
                //获取经纬度位置信息，存入本地数据库缓存
                currentLocation.setLatitude(latitude);
                currentLocation.setLongitude(longitude);
                currentLocation.setAdminArea(province);
                currentLocation.setLocality(city);
                currentLocation.setSubLocality(district);
                currentLocation.saveOrUpdate("id = 1");
            }
        });
    }

    public void requestMoji(String adminArea, String locality, String subLocality) {
        if (!canIn() || (TextUtils.isEmpty(adminArea) && TextUtils.isEmpty(locality))) {
            return;
        }
        LogUtils.e("请求一次墨迹接口");
        String url = "http://apis.duiopen.com/apis/weather/forecast/specific?" +
                "productId=" + productId + "&" +
                "deviceId=" + BaseUtils.getDeviceId() + "&" +
                "apikey=" + apiKey + "&" +
                "pkg=" + pkg + "&" +
                "signatuerSha256=" + signatuerSha256 + "&" +
                "buildVariant=" + buildVariant;
        List<String> strings = new ArrayList<>();
        strings.add("moji");
        MojiBean mojiBean = new MojiBean();
        mojiBean.setProvince(adminArea.replace("市", ""));//省
        mojiBean.setCity(locality);//市
//        mojiBean.setArea(subLocality);//区
        mojiBean.setSource(strings);
        OkHttpUtils.requestBodyPost(mContext, url, mojiBean, new StringCallBack<MojiEntity>() {
            @Override
            public void onResponse(MojiEntity bean, int id) {
                WeatherManager.getInstance(mContext).setMojiEntity(bean);
                //解决语音查询各个地区天气时，轮播图、天气中心等界面同步更新的问题；
                CurrentLocation last = LitePal.findLast(CurrentLocation.class);
                if (last != null) {
                    LogUtils.e("locality： " + locality
                            + "，last.getLocality()：" + last.getLocality());
                    if (locality.contains(last.getLocality())) {
                        //通知天气信息已更新
                        GlobalPublisher.Notify(GlobalPublisher.WEATHER_UPDATE);
                    }
                } else {
                    //通知天气信息已更新
                    GlobalPublisher.Notify(GlobalPublisher.WEATHER_UPDATE);
                }
                GlobalPublisher.Notify(GlobalPublisher.WEATHER_UPDATE_FOR_WEATHER_CENTER);
            }

            @Override
            public void onError(okhttp3.Call call, Exception e, int id) {
                super.onError(call, e, id);
                LogUtils.e("墨迹天气获取失败：msg = " + e.getMessage());
            }
        });
    }

    private boolean canIn() {
        //再次请求时间
        long ct = System.currentTimeMillis();
        if (ct - sTime < 2000) {
            LogUtils.d("2s内限制天气接口请求");
            return false;
        }
        sTime = ct;
        return true;
    }

    public MojiEntity getMojiEntity() {
        return mMojiEntity;
    }

    public void setMojiEntity(MojiEntity mMojiEntity) {
        this.mMojiEntity = mMojiEntity;
    }
}
